package com.example.security.funtion;

import com.example.sys.auth.service.SysAuthService;
import com.example.sys.module.service.SysModuleService;
import com.example.sys.org.service.SysElementService;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public abstract class SysAbstractFunction extends AbstractFunction implements ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware {

    Logger logger = LoggerFactory.getLogger(getClass());

    public static final String ID = "id";

    private ApplicationContext applicationContext;

    private SysAuthService sysAuthService;

    private SysElementService sysElementService;

    private SysModuleService sysModuleService;

    @Override
    public String getName() {
        return getClass().getSimpleName();
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            AviatorEvaluator.addFunction(this);
        }
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public SysAuthService getSysAuthService() {
        if (sysAuthService == null) {
            sysAuthService = getApplicationContext().getBean(SysAuthService.class);
        }
        return sysAuthService;
    }

    public SysElementService getSysElementService() {
        if (sysElementService == null) {
            sysElementService = getApplicationContext().getBean(SysElementService.class);
        }
        return sysElementService;
    }

    public SysModuleService getSysModuleService() {
        if (sysModuleService == null) {
            sysModuleService = getApplicationContext().getBean(SysModuleService.class);
        }
        return sysModuleService;
    }
}
